﻿// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;
using System.Data.SqlClient;
using System.Data;

namespace InterpriseSuiteEcommerceCommon
{
    public class RedirectLogic
    {
        public static SortedDictionary<string, string> redirectURL; // <old path> / <new path>

        public static bool Process()
        {
            if (HttpContext.Current.Request.Url.PathAndQuery.Length > HttpContext.Current.Request.ApplicationPath.Length)
            {
                string path = HttpContext.Current.Request.Url.PathAndQuery.Substring(CommonLogic.IIF(HttpContext.Current.Request.ApplicationPath.Length == 1, HttpContext.Current.Request.ApplicationPath.Length ,HttpContext.Current.Request.ApplicationPath.Length + 1)).ToLowerInvariant();
                if (IsToRedirect(path))
                {
                    HttpContext.Current.Response.RedirectPermanent(HttpContext.Current.Request.ApplicationPath + "/" + redirectURL[path], true);
                    //HttpContext.Current.Response.RedirectPermanent(redirectURL[path], true);
                }
            }
            return false;
        }

        public static void InitializeRedirectURL()
        {
            redirectURL = new SortedDictionary<string, string>();

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, string.Format("SELECT OldPath, NewPath FROM EcommerceStoreURLRedirect with (NOLOCK) WHERE WebsiteCode = {0}", DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode))))
                {
                    while (reader.Read())
                    {
                        if (!redirectURL.ContainsKey(DB.RSField(reader, "OldPath").ToLowerInvariant()))
                        {
                            redirectURL.Add(DB.RSField(reader, "OldPath").ToLowerInvariant(), DB.RSField(reader, "NewPath").ToLowerInvariant());
                        }
                    }
                }
            }            
        }

        private static bool IsToRedirect(string path)
        {
            if (redirectURL.ContainsKey(path) && redirectURL[path] != string.Empty)
            {
                return true;
            }
            return false;
        }
    }
}
